import {
  request
} from "../../utils/requestUtils"
import { userBehavior } from '../../behaviors/userBehavior'


// pages/customer_shop_cart/index.js
Page({
  behaviors: [userBehavior],
  // 组件的初始数据
  data: {
    totalAmount: 0, // 总金额
    checkedAll: false,
    cartList: [],
    emptyDes: '还没有添加商品，快去添加吧～'
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    this.getCart()
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    this.getTabBar().setData({
      active: 2
    })
    this.setData({
      checkedAll:false
    })
    console.log('测22')

    this.getCart()
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  },
    //获取购物车数量
    async getCartNum(){
      const result = await request({
        url: `/bus/customer/cart/cartNum`,
        method: "GET"
      })
      if(result.data.code == 200){
        this.setCarNum(result.data.data)
      }
    },
  // 查询我的购物车
  async getCart() {
    const result = await request({
      url: `/bus/customer/cart/query`,
      method: "GET"
    })
    if (result.data.code == 200) {
      result.data.data.forEach(v => v.checked = false)
      this.setData({
        cartList: result.data.data
      })
    }
  },
  // 提交
  async onSubmit(e) {
    let cartListTemp = JSON.parse(JSON.stringify(this.data.cartList)).filter(v => v.checked)
    if(!cartListTemp || cartListTemp.length ==0){
      wx.showToast({
        title: '请选择要结算的商品',
        mask: true,
        icon: 'none',
        duration: 3000
      })
      return;
    }
    cartListTemp.forEach(v=>v.checked = 2)
    const result = await request({
      url: `/bus/customer/cart/editBatch`,
      method: "PUT",
      data: cartListTemp
    })
    if(result.data.code==200){
      this.getCartNum()
      setTimeout(() => {
        wx.navigateTo({
          url: '/pages/customer_pay/index',
        })
      }, 500);
    

    }
  },
  // 删除购物车商品
  async delete(event){
    const modalRes = await wx.showModal({
      content: '删除该商品 ?'
    })
    if (modalRes.cancel) return
    const result = await request({
      url: `/bus/customer/cart/`+event.target.dataset.id,
      method: "DELETE"
    })
    if(result.data.code == 200){
      this.getCartNum()
      this.getCart()
    }
  },
  // 是否全选
  onChange(event) {
    const {
      detail
    } = event
    const newCartList = JSON.parse(JSON.stringify(this.data.cartList))
    newCartList.forEach((item) => (item.checked = detail))
    this.setData({
      checkedAll: detail,
      cartList: newCartList
    })
    this.calculateTotalAmount()
  },
  // 单选
  onCheck(event) {
    const {
      detail
    } = event
    const {
      id,
      index
    } = event.target.dataset
    this.setData({
      [`cartList[${index}].checked`]: detail
    })
    let cartListTemp = this.data.cartList.filter(v => v.checked)
    this.setData({
      checkedAll: cartListTemp.length == this.data.cartList.length
    })
    this.calculateTotalAmount()
  },
  // 计算总金额，最好使用计算属性
  calculateTotalAmount() {
    let totalAmountTemp = 0
    this.setData({
      totalAmount: totalAmountTemp * 100
    })
    if (!this.data.cartList || this.data.cartList.length == 0) return
    let cartListTemp = this.data.cartList.filter(v => v.checked)
    if (!cartListTemp || cartListTemp.length == 0) return
     totalAmountTemp = cartListTemp.reduce((sum, item) => {
       console.log('item.price', item.salesBeforePrice * item.carNum)
      return sum + (item.salesBeforePrice * item.carNum);
    }, 0)
    this.setData({
      totalAmount: totalAmountTemp * 100
    })

  },
  // 修改商品数量
  numberChange(event){
    const { detail } = event
    const { id,  index } = event.target.dataset
    this.setData({
      [`cartList[${index}].carNum`]: detail
    })
    this.calculateTotalAmount()
  },
  toBy(){
    console.log('2321')
    wx.switchTab({
      url: '/pages/customer_index/index',
    })

  }
})
